<template>
  <t-layout style="height: 100vh;" v-if="defaultStore.Token !== ''">
    <t-header class="disable-selection">
      <t-head-menu value="item1" height="120px">
        <template #logo>
          <template v-if="!asideCollapsed">
            <div style="width: 230px;overflow: hidden" class="r-fx-row-c">
              <LogoSVG/>
            </div>
          </template>
          <template v-else>
            <span class="textLogo">
              Admin
            </span>
          </template>
        </template>
        <div class="r-fx-row-czc">
          <t-button theme="default" shape="circle" variant="text" size="large"
                    @click="asideCollapsed = !asideCollapsed">
            <template #icon>
              <template v-if="!asideCollapsed">
                <MenuUnfoldIcon/>
              </template>
              <template v-else>
                <MenuFoldIcon/>
              </template>
            </template>
          </t-button>
          <div style="width: 1em"></div>
          <t-tag theme="primary" variant="light" size="small">
            <template #icon>
              <i class="iconfont icon-shenfenzheng"/>
            </template>
            <div style="margin-left: 0.5em">
              {{ `${userStore.Profile.user.id}` }}
            </div>
          </t-tag>
          <div style="width: 1em"></div>
          <t-tag theme="primary" variant="light" size="small">
            <template #icon>
              <TimeFilledIcon/>
            </template>
            {{ toLocalTimeByTimeSecond(TimeInfo.CurTime) }}
          </t-tag>
          <div style="width: 1em"></div>
          <t-tag theme="primary" variant="light" size="small">
            <template #icon>
              <HourglassIcon/>
            </template>
            {{ TimeInfo.TokenTime }}
          </t-tag>
        </div>
        <template #operations>
          <div style="width: 5em"></div>
        </template>
      </t-head-menu>
    </t-header>
    <t-layout>
      <t-aside class="aside disable-selection" v-model:expanded="menuData.curSelect"
               :style="asideCollapsed ? 'width:64px':''">
        <t-menu v-model:value="menuData.curSelect" :collapsed="asideCollapsed"
                expandMutex @change="OnSelect">
          <t-submenu value="my">
            <template #icon>
              <UserIcon/>
            </template>
            <template #title>
              <span>个人中心</span>
            </template>
            <t-menu-item value="my/info">
              <template #icon>
                <UserCircleIcon/>
              </template>
              我的信息
            </t-menu-item>
          </t-submenu>
          <template v-for="it in Menu.List">
            <t-submenu :value="`${it.path}`">
              <template #icon>
                <t-icon :name="it.icon"/>
              </template>
              <template #title>
                <span>{{ it.label }}</span>
              </template>
              <template v-if="it.items != null">
                <template v-for="it2 in it.items">
                  <t-menu-item :value="`${it.path}/${it2.path}`">
                    <template #icon>
                      <t-icon :name="it2.icon"/>
                    </template>
                    {{ it2.label }}
                  </t-menu-item>
                </template>
              </template>
            </t-submenu>
          </template>
        </t-menu>
      </t-aside>
      <t-layout>
        <t-content>
          <t-space>
            <t-tabs theme="card" size="medium" v-model="Menu.TabValue"
                    @change="ChangeTab" @remove="RemoveTab">
              <t-tab-panel value="/admin/my/info">
                <template #label>
                  <UserCircleIcon/>
                </template>
              </t-tab-panel>
              <template v-for="tab in Menu.Tabs">
                <t-tab-panel
                    :label="tab.label"
                    :removable="tab.removable"
                    :value="tab.value"
                />
              </template>
            </t-tabs>
          </t-space>
          <t-card size="small" class="content">
            <router-view v-slot="{ Component }">
              <keep-alive :include="Menu.RouterViewKeepAlive">
                <component :is="Component"/>
              </keep-alive>
            </router-view>
          </t-card>
        </t-content>
      </t-layout>
    </t-layout>
  </t-layout>
</template>
<script lang="ts" setup>
import LogoSVG from "../../assets/svg/assets-t-logo.svg"
import {onMounted, reactive, ref} from "vue";
import {
  MenuUnfoldIcon,
  MenuFoldIcon,
  UserIcon,
  UserCircleIcon,

} from "tdesign-icons-vue-next"
import {MenuValue, TdTabPanelProps} from "tdesign-vue-next";
import {RouteRecordRaw, useRouter} from "vue-router";
import {getDefaultStore} from "../../store/modules/default";
import {GetMenu, Menu, AddNewTab} from "./menu";
import {curTimeUnix, toLocalTimeByTimeSecond} from "../../tool/time";
import {TimeFilledIcon, HourglassIcon} from "tdesign-icons-vue-next";
import {getUserStore} from "../../store/modules/user";

const router = useRouter()
const userStore = getUserStore()
const defaultStore = getDefaultStore()
const asideCollapsed = ref(false)

const TimeInfo = reactive({
  CurTime: 0,
  TokenTime: 0,
})

// OnSelect 点击了导航菜单项
const OnSelect = (value: MenuValue) => {
  menuData.curSelect = value.toString()
  window.sessionStorage.setItem("navSelect", menuData.curSelect)
  AddNewTab('/admin/' + value)
  router.push({
    path: '/admin/' + value,
  })
}

// ChangeTab 点击了标签栏项
const ChangeTab = (value: string) => {
  OnSelect(value.substring(7, 1024))
}

// RemoveTab 删除了某个标签
const RemoveTab = (p: any) => {
  Menu.Tabs.splice(p.index - 1, 1)
  Menu.RouterViewKeepAlive.splice(p.index - 1, 1)
  if (Menu.Tabs.length <= 0) {
    Menu.TabValue = '/admin/my/info'
  } else {
    if (p.index - 2 < 0) {
      Menu.TabValue = `${Menu.Tabs[0].value}`
    } else {
      Menu.TabValue = `${Menu.Tabs[p.index - 2].value}`
    }
  }
  OnSelect(Menu.TabValue.substring(7, 1024))
}

const menuData = reactive({
  curSelect: 'my/info', //当前选中的
  list: new Array<TdTabPanelProps>(),
})

onMounted(async () => {
  if (curTimeUnix() > defaultStore.tokenExpirationTime) {
    await router.push({
      path: '/login'
    })
    return
  }
  await GetMenu()
  await initRouter()
  menuData.curSelect = window.sessionStorage.getItem("navSelect") || "my/info"
  OnSelect(menuData.curSelect)

  setInterval(() => {
    TimeInfo.CurTime = curTimeUnix()
    TimeInfo.TokenTime = defaultStore.tokenExpirationTime - curTimeUnix()
  }, 1000)
})

//加载所有的vue文件
const modules = import.meta.glob('./*/*.vue')
//初始化路由
const initRouter = async () => {
  let admin = router.getRoutes().find(it => {
    if (it.name === "admin") {
      return it
    }
  })
  if (admin === undefined) {
    return
  }
  router.removeRoute('admin')
  for (let i = 0; i < Menu.List.length; i++) {
    let it1 = Menu.List[i]
    let newRoute = {
      path: it1.path,
      children: new Array<RouteRecordRaw>(),
    }
    for (let j = 0; j < Menu.List[i].items.length; j++) {
      let it2 = Menu.List[i].items[j]
      if (modules[`./${it1.path}/${it2.path}.vue`] === undefined) {
        continue //vue文件不存在，就直接跳过该路由的注册
      }
      let name = `${it1.path}_${it2.path}`
      let newItem = {
        path: '/admin/' + it1.path + "/" + it2.path,
        name: name,
        component: modules[`./${it1.path}/${it2.path}.vue`],
        meta: {title: it2.title},
      }
      newRoute.children.push(newItem)
    }
    admin.children.push(newRoute)
  }
  router.addRoute(admin)
}

</script>
<style scoped>
.aside {
  border-top: 1px solid var(--td-component-border);
}

.textLogo {
  font-weight: 700;
  margin-left: 1em;
}

.content {
  min-height: 50vh;
  max-height: 86vh;
  overflow: auto;
}
</style>